import ctypes
import json
import os
import re
import subprocess
import sys

from utils.logger import log


class EventBus:
    def __init__(self):
        self._listeners = {}

    def subscribe(self, event_name, callback):
        """订阅某个事件"""
        self._listeners.setdefault(event_name, []).append(callback)

    def unsubscribe(self, event_name, callback):
        """取消订阅"""
        if event_name in self._listeners:
            self._listeners[event_name].remove(callback)

    def publish(self, event_name, *args, **kwargs):
        """广播事件"""
        for callback in self._listeners.get(event_name, []):
            callback(*args, **kwargs)


class CommonUtils:

    password = "<PASSWORD>"

    @staticmethod
    def extract_seconds(text):
        # 尝试匹配“x分钟x秒”
        match_full = re.search(r'(\d+)分钟(\d+)秒', text)
        if match_full:
            minutes = int(match_full.group(1))
            seconds = int(match_full.group(2))
            return minutes * 60 + seconds

        # 尝试匹配仅“x秒”
        match_seconds = re.search(r'(\d+)秒', text)
        if match_seconds:
            return int(match_seconds.group(1))

        # 如果都匹配不到，返回0
        return 0

    @staticmethod
    def check_adb_connection(ip, port):
        adb_path = os.path.join(account_config()["mumu_dir"], "shell", "adb.exe")

        try:
            result = subprocess.run([adb_path, 'devices'], capture_output=True, text=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
            lines = result.stdout.strip().splitlines()
            for line in lines:
                if f"{ip}:{port}" in line:
                    log.info(f" adb 设备 {ip}:{port} 已连接")
                    return True

            try:
                log.info(f"尝试连接 adb 设备 {ip}:{port} ...")
                result = subprocess.run([adb_path, 'connect', f"{ip}:{port}"], capture_output=True, text=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)

                if f"connected to {ip}:{port}" in result.stdout:
                    log.info(f"连接 adb 设备：{ip}:{port} 成功")
                    return True

                log.info(f"连接失败：{result.stdout.strip()}")
                return False
            except Exception as e:
                log.info(f"连接失败：{e}")
                return False
        except:
            return False

    @staticmethod
    def get_pk(ip, port, name, task=None):
        if task:
            return f"{ip}:{port}-{name}-{task}"
        else:
            return f"{ip}:{port}-{name}"

    @staticmethod
    def resource_path(rel_path: list):
        try:
            base = sys._MEIPASS  # PyInstaller打包后的临时目录
        except AttributeError:
            base = os.path.abspath(".")  # 普通运行
        return os.path.join(base, *rel_path)


class FullGXException(Exception):
    pass


def account_config(path=False):
    config_path = os.path.join(os.getcwd(), "config.json")
    if not os.path.exists(config_path):
        config_path = r'D:\little_empire\config.json'
    if not os.path.exists(config_path):
        response = ctypes.windll.user32.MessageBoxW(
            0,
            "缺少配置文件！",
            "程序错误",
            0x10  # 图标为 ❌ 错误
        )

        # 用户点击确认按钮（MessageBox 返回 1）
        if response == 1:
            sys.exit(1)

    with open(config_path, "r", encoding="utf-8") as f:
        config = json.load(f)
    return config if not path else config_path